﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TSharp.Core.Util.Properties;

namespace TSharp.Core.Util.Numeric
{
    internal static class BinaryCodec
    {
        // Methods
        public static byte[] GetBytes(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if ((value.Length % 8) != 0)
            {
                throw new FormatException(Resources.InvalidCharacterCount);
            }
            byte[] buffer = new byte[value.Length / 8];
            for (int i = 0; i < buffer.Length; i++)
            {
                string s = value.Substring(i * 8, 8);
                for (int j = 0; j < 8; j++)
                {
                    int numericValue = (int)char.GetNumericValue(s, j);
                    if (numericValue < 0)
                    {
                        throw new FormatException(Resources.IllegalBinaryCharacter);
                    }
                    buffer[i] = (byte)(buffer[i] + ((byte)(numericValue << (7 - j))));
                }
            }
            return buffer;
        }

        public static string GetString(byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            StringBuilder builder = new StringBuilder(value.Length * 8);
            foreach (byte num in value)
            {
                StringBuilder builder2 = new StringBuilder(8);
                byte num2 = num;
                for (int i = 0; i < 8; i++)
                {
                    builder2.Append(((num2 % 2) != 0) ? '1' : '0');
                    num2 = (byte)(num2 >> 1);
                }
                char[] array = builder2.ToString().ToCharArray();
                Array.Reverse(array);
                builder.Append(array);
            }
            return builder.ToString();
        }
    }


}
